package net.hky365.lowcode.magic.utils;

import cn.hutool.cache.impl.TimedCache;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ssssssss.script.MagicScriptContext;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Objects;

/**
 * 日志帮助类
 *
 * @author hl-king
 */
public class LoggerHelper {
    private LoggerHelper() {
    }

    private static final long CACHE_TIME = Duration.of(30, ChronoUnit.MINUTES).toMillis();
    private static final TimedCache<String, Logger> loggerCache = new TimedCache<>(CACHE_TIME);


    @NotNull
    public static Logger getLogger(MagicScriptContext context) {
        String loggerName = Objects.toString(context.getScriptName(), "Unknown");
        return loggerCache.get(loggerName, true, () -> LoggerFactory.getLogger(getLoggerName(context)));
    }

    @NotNull
    public static String getLoggerName(MagicScriptContext context) {
        String loggerName = Objects.toString(context.getScriptName(), "Unknown");

        // 一共有如下两种情况, 第一种通过将 url 路径转为包格式来进行控制, 第二种通过将名称转为包格式来进行控制
        // 模板/获取模板信息(/yk/amis/template/detail/{id})
        // 模板/获取模板信息

        int index = loggerName.lastIndexOf('(');
        if (index > -1 && loggerName.endsWith(")")) {
            // 第一种情况
            loggerName = loggerName.substring(index + 1, loggerName.length() - 1).replace("/", ".") + loggerName;
            loggerName = loggerName.replaceAll("^\\.", "");
        } else {
            loggerName = loggerName.replace("/", ".") + "(" + loggerName + ")";
            loggerName = loggerName.replaceAll("^\\.", "");
        }
        return loggerName;
    }
}
